/*
 Copyright 2009 Abdulla Abdurakhmanov (abdulla@latestbit.com)
 Original sources are available at www.latestbit.com

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.

 CommandProcessor.cpp. Created on: 22.09.2009 15:22:51 
 */

#include "smartobjects/core/CommandProcessor.hpp"
#include "smartobjects/IServerSkeleton.hpp"
#include "smartobjects/coders/StdNetworkCommand.hpp"
#include "smartobjects/coders/StdPacketFormer.hpp"


namespace smartobjects {

CommandProcessor::CommandProcessor(ISmartBus* poBus) :
		m_poBus(poBus),
		m_poAsyncCallsTimer( new Timer(
			(boost::format("CommandProcessorTimer[%1%]") %this).str()) ),
		m_poTlsSyncContext(&boost::intrusive_ptr_release),
		m_poDefaultProcessorHandler( new DefaultCommandProcessorHandler(this) ) {
	m_poBus->addRef();
}

CommandProcessor::~CommandProcessor() {
	releaseAsyncCalls();

	if(m_poAsyncCallsTimer) {
		m_poAsyncCallsTimer->cancelAll();
		m_poAsyncCallsTimer->release();
		m_poAsyncCallsTimer = NULL;
	}

	releaseAndClear(m_poDefaultProcessorHandler);
	releaseBuffers();

	releaseAndClear(m_poBus);
}

void CommandProcessor::releaseAsyncCalls() {
	typedef std::list < AsyncCallQueueItem > TempCallsList;
	TempCallsList aTempCallsSet;

	boost::unique_lock<boost::recursive_mutex> oAsyncCallsLock(m_mxAsyncCalls);
	for(AsyncCallsMap::iterator it = m_mAsyncCalls.begin(); it!=m_mAsyncCalls.end(); it++) {
		if(it->second.getSyncCallContext()!=NULL) {
			aTempCallsSet.push_back(it->second);
		}
	}
	m_mAsyncCalls.clear();
	oAsyncCallsLock.unlock();

	for(TempCallsList::iterator it = aTempCallsSet.begin(); it!=aTempCallsSet.end(); it++) {
		boost::unique_lock<boost::mutex> oSyncLock( it->getSyncCallContext()->getSyncCallLock() );
		it->getSyncCallContext()->setSyncCallResponse(NULL);
		it->getSyncCallContext()->getSyncCallEvent().notify_one();
	}
}

void CommandProcessor::releaseBuffers() {
	boost::unique_lock<boost::recursive_mutex> oBuffersLock(m_mxBuffersCache);
	foreach(ByteBuffer* poBuffer, m_aBuffersCache) {
		poBuffer->release();
	}
	m_aBuffersCache.clear();
	oBuffersLock.unlock();
}

void CommandProcessor::sendAsyncRequest(
		ConnectionHandler* poConnectionHandler,
		INetworkCommand* poRequest,
		ICommandProcessorHandler* poHandler,
		RefObject* poUserObject,
		unsigned int nTimeoutInSec) {
	sendAsyncRequest(poConnectionHandler, poRequest, poHandler, poUserObject, nTimeoutInSec, NULL);
}

void CommandProcessor::sendAsyncRequest(
		ConnectionHandler* poConnectionHandler,
		INetworkCommand* poRequest,
		ICommandProcessorHandler* poHandler,
		RefObject* poUserObject,
		unsigned int nTimeoutInSec,
		SyncCallContext* poSyncCallContext) {

	if(!poRequest->isRequest())
		throw SystemException("Internal error: Unable to send response as request!");
	if(!poRequest->isSerialized())
		throw SystemException("Internal error: Request is not serialized before to send");


	Timer::TimerId nTimerId = (Timer::TimerId)poRequest->getMessageId();
	boost::unique_lock<boost::recursive_mutex> oLock(m_mxAsyncCalls);
	m_mAsyncCalls.insert( AsyncCallsMap::value_type(
			nTimerId,
			AsyncCallQueueItem(poRequest, poHandler, poUserObject, poSyncCallContext)
	) );
	oLock.unlock();

	m_poAsyncCallsTimer->schedule(nTimerId, nTimeoutInSec * 1000,
			boost::bind(&CommandProcessor::onAsyncCallHandleTimeout, this, _1)
	);

	try {
		poConnectionHandler->getConnection()->send(poRequest->getBuffer());
	}
	catch(const SystemException&) {
		m_poAsyncCallsTimer->cancel(nTimerId);
		boost::unique_lock<boost::recursive_mutex> oLock(m_mxAsyncCalls);
		m_mAsyncCalls.erase(nTimerId);
		throw;
	}
}

void CommandProcessor::onAsyncCallHandleTimeout(Timer::TimerId nTimerId) {
	bool bIsFound = false;
	AsyncCallQueueItem oItem;
	boost::unique_lock<boost::recursive_mutex> oLock(m_mxAsyncCalls);
	AsyncCallsMap::iterator oIter = m_mAsyncCalls.find(nTimerId);
	if(oIter!=m_mAsyncCalls.end()) {
		oItem = oIter->second;
		m_mAsyncCalls.erase(oIter);
		bIsFound = true;
	}
	oLock.unlock();
	if(bIsFound) {
		if(!oItem.getSyncCallContext()) {
			if( oItem.getCommandProcessorHandler()!=NULL ) {
				oItem.getCommandProcessorHandler()->onResponseTimeout(
						oItem.getRequest(),
						oItem.getUserRefObject()
				);
			}
		}
		else {
			boost::unique_lock<boost::mutex> oLock(oItem.getSyncCallContext()->getSyncCallLock());
			oItem.getSyncCallContext()->setSyncCallResponse(NULL);
			oItem.getSyncCallContext()->getSyncCallEvent().notify_one();
		}
	}
}

INetworkCommand* CommandProcessor::sendSyncRequest(
		ConnectionHandler* poConnectionHandler,
		INetworkCommand* poRequest,
		unsigned int nTimeoutInSec) {

	if(!poRequest->isRequest())
		throw SystemException("Internal error: Unable to send response as request!");
	if(!poRequest->isSerialized())
		throw SystemException("Internal error: Request is not serialized before to send");

	INetworkCommand* poResponse = NULL;
	if(m_poTlsSyncContext.get()==NULL) {
		m_poTlsSyncContext.reset( new SyncCallContext() );
	}
	boost::intrusive_ptr<SyncCallContext> poSyncCallContext ( (SyncCallContext*)m_poTlsSyncContext.get() , true );
	boost::unique_lock<boost::mutex> oLock(poSyncCallContext->getSyncCallLock());
	sendAsyncRequest(poConnectionHandler, poRequest, NULL, NULL, nTimeoutInSec, poSyncCallContext.get());
	poSyncCallContext->getSyncCallEvent().wait(oLock);
	poResponse = poSyncCallContext->getSyncCallResponse();
	if(!poResponse)
		throw SmartBusSystemException("Timeout to response");
	poResponse->addRef();
	return poResponse;
}

void CommandProcessor::sendResponse(
		ConnectionHandler* poConnectionHandler,
		INetworkCommand* poResponse) {
	if(!poResponse->isResponse())
		throw SystemException("Internal error: Unable to send request as response!");
	if(!poResponse->isSerialized())
		throw SystemException("Internal error: Response is not serialized before to send");

	try {
		poConnectionHandler->getConnection()->send( poResponse->getBuffer() );
		returnBufferToCache(poResponse);
	}
	catch(const SystemException&) {
		returnBufferToCache(poResponse);
		throw;
	}

}

void CommandProcessor::onReceived(ConnectionHandler* poHandler, ByteBuffer* poBuffer) throw() {
	boost::intrusive_ptr<IDataTypesCoder> poCoder (m_poBus->createDataTypesCoder(), false);
	StdNetworkCommand* poCommand = new StdNetworkCommand(poBuffer, poCoder.get());
	try {
		poCommand->deserialize();
		if(poCommand->isRequest()) {
			onReceivedRequest(poHandler, poCommand);
		}
		else {
			onReceivedResponse(poHandler, poCommand);
		}
	}
	catch(const SystemException& ex) {
		onReceiveError(poHandler, ex.what());
	}
	poCommand->release();
}

void CommandProcessor::onReceivedRequest(ConnectionHandler* poConnectionHandler, INetworkCommand* poRequest) {
	ByteBuffer* poBuffer = poRequest->getBuffer();
	ByteBuffer* poCopyOfBuffer = getBufferFromCache(poBuffer->getLenFromPos());
	poCopyOfBuffer->append ( poBuffer->getDataAtPos(), poBuffer->getLenFromPos() );
	poRequest->setBuffer ( poCopyOfBuffer );
	poCopyOfBuffer->release();

	ICommandProcessorHandler* poProcessorHandler = NULL;
	boost::shared_lock<boost::shared_mutex> oSharedLock(m_mxFilters);
	if(!poRequest->getInstanceId().empty()) {
		CommandHandlerFilters::left_const_iterator oIter = m_mHandlersByInstanceId.left.find(poRequest->getInstanceId());
		if(oIter != m_mHandlersByInstanceId.left.end()) {
			poProcessorHandler = oIter->second;
		}
	}
	if(poProcessorHandler == NULL) {
		CommandHandlerFilters::left_const_iterator oIter = m_mHandlersByDest.left.find(poRequest->getDestination());
		if(oIter != m_mHandlersByDest.left.end()) {
			poProcessorHandler = oIter->second;
		}
	}

	if(poProcessorHandler == NULL ) {
		poProcessorHandler = m_poDefaultProcessorHandler;
	}
	poProcessorHandler->addRef();
	oSharedLock.unlock();

	try {
		poProcessorHandler->onRequestReceived(poConnectionHandler, poRequest);
	}
	catch(const SystemException &ex) {
		onReceiveError(poConnectionHandler, ex.what());
	}

	poProcessorHandler->release();
}

void CommandProcessor::onReceivedResponse(ConnectionHandler* poHandler, INetworkCommand* poResponse) {
	bool bIsFound = false;
	AsyncCallQueueItem oItem;
	boost::unique_lock<boost::recursive_mutex> oLock(m_mxAsyncCalls);
	AsyncCallsMap::iterator oIter = m_mAsyncCalls.find(poResponse->getMessageId());
	if(oIter!=m_mAsyncCalls.end()) {
		oItem = oIter->second;
		m_mAsyncCalls.erase(oIter);
		bIsFound = true;
	}
	oLock.unlock();

	if(bIsFound) {
		m_poAsyncCallsTimer->cancel(poResponse->getMessageId());
		reuseRequestBuffer ( oItem.getRequest(), poResponse );
		if(!oItem.getSyncCallContext()) {
			if(oItem.getCommandProcessorHandler()!=NULL) {
				oItem.getCommandProcessorHandler()->onResponseReceived(
						poHandler, oItem.getRequest(), poResponse, oItem.getUserRefObject() );
			}
		}
		else {
			boost::unique_lock<boost::mutex> oLock(oItem.getSyncCallContext()->getSyncCallLock());
			oItem.getSyncCallContext()->setSyncCallResponse(poResponse);
			oItem.getSyncCallContext()->getSyncCallEvent().notify_one();
		}
	}
}

void CommandProcessor::reuseRequestBuffer(INetworkCommand* poRequest, INetworkCommand* poResponse) {
	ByteBuffer* poBuffer = poRequest->getBuffer();
	poBuffer->addRef();
	poRequest->setBuffer(NULL);
	poBuffer->clear();
	poBuffer->append ( poResponse->getBuffer()->getDataAtPos(), poResponse->getBuffer()->getLenFromPos() );
	poResponse->setBuffer( poBuffer );
	poBuffer->release();
}

void CommandProcessor::returnBufferToCache(INetworkCommand* poCommand) {
	boost::unique_lock<boost::recursive_mutex> oLock(m_mxBuffersCache);
	ByteBuffer* poBuffer = poCommand->getBuffer();
	poBuffer->addRef();
	poCommand->setBuffer(NULL);
	m_aBuffersCache.push_back( poBuffer );
}

ByteBuffer* CommandProcessor::getBufferFromCache(unsigned int nInitSize) {
	ByteBuffer* poResult = NULL;
	boost::unique_lock<boost::recursive_mutex> oLock(m_mxBuffersCache);

	if(nInitSize < 256)
		nInitSize = 256;

	if( m_aBuffersCache.empty() ) {
		poResult = new ByteBuffer(nInitSize, StdPacketFormer::MAX_PACKET_SIZE);
	}
	else {
		poResult = m_aBuffersCache.front();
		m_aBuffersCache.pop_front();
		poResult->clear();
	}
	return poResult;
}

void CommandProcessor::onReceiveError(ConnectionHandler* poHandler, const std::string& sErrorMessage) throw() {

}

void CommandProcessor::onWriteError(ConnectionHandler* poHandler, const std::string& sErrorMessage) throw() {

}


void CommandProcessor::addRequestHandler (
		ICommandProcessorHandler* poHandler,
		const std::string& sDestinationFilter ) {
	addRequestHandler(poHandler, sDestinationFilter, "");
}

void CommandProcessor::addRequestHandler (
		ICommandProcessorHandler* poHandler,
		const std::string& sDestinationFilter,
		const std::string& sInstanceIdFilter ) {

	boost::unique_lock<boost::shared_mutex> oLock(m_mxFilters);
	ICommandProcessorHandler* poAlreadyBound = NULL;
	if(sInstanceIdFilter.empty()) {
		CommandHandlerFilters::left_const_iterator oIter = m_mHandlersByDest.left.find(sDestinationFilter);
		if(oIter!=m_mHandlersByDest.left.end()) {
			if(poHandler!= oIter->second)
				throw SystemException(boost::format("Filter '%1%' is already bound to another command processor handler") %sDestinationFilter);
			else
				poAlreadyBound = oIter->second;
		}

		if(poAlreadyBound == NULL) {
			m_mHandlersByDest.left.insert( CommandHandlerFilters::left_value_type( sDestinationFilter,  poHandler ) );
		}
	}
	else {
		CommandHandlerFilters::left_const_iterator oIter = m_mHandlersByInstanceId.left.find(sInstanceIdFilter);
		if(oIter!=m_mHandlersByInstanceId.left.end()) {
			if(poHandler!= oIter->second)
				throw SystemException(boost::format("Filter '%1%' is already bound to another command processor handler") %sInstanceIdFilter);
			else
				poAlreadyBound = oIter->second;
		}

		if(poAlreadyBound == NULL) {
			m_mHandlersByInstanceId.left.insert( CommandHandlerFilters::left_value_type(sInstanceIdFilter, poHandler ) );
		}
	}
}

void CommandProcessor::addRequestHandler (
		ICommandProcessorHandler* poHandler,
		IServerSkeleton* poSmartObject) {
	addRequestHandler(poHandler, poSmartObject->getInterfaceId(), poSmartObject->getInstanceId());
	const char** aSupportedInterfaces = poSmartObject->getSupportedInterfaces();
	if ( aSupportedInterfaces ) {
		unsigned int nIdx = 0;
		while(aSupportedInterfaces[nIdx]) {
			addRequestHandler(poHandler, aSupportedInterfaces[nIdx++]);
		}
	}
}

void CommandProcessor::delRequestHandler ( ICommandProcessorHandler* poHandler ) {
	boost::unique_lock<boost::shared_mutex> oLock(m_mxFilters);
	m_mHandlersByInstanceId.right.erase(poHandler);
	m_mHandlersByDest.right.erase(poHandler);
}

unsigned int CommandProcessor::getAsyncCallsQueueSize() {
	boost::unique_lock<boost::recursive_mutex> oLock(m_mxAsyncCalls);
	return m_mAsyncCalls.size();
}

}
